<?php

namespace App\Console\Commands;

use App\Library\Logger;
use App\Models\ScreenCustomerTemp;
use Carbon\Carbon;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\IOFactory;

class ImportScreenTemp extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:screen_temp';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入运营大屏临时数据';

    private $logger;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->logger = new Logger('commands/import_screen_temp');
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bench = new \Ubench();
        $bench->start();

        $this->handleImport();

        $bench->end();
        $this->logger->debug("time used: " . $bench->getTime());
        $this->logger->debug("memory used: " . $bench->getMemoryUsage());
    }

    private function handleImport()
    {
        $this->logger->info("导入数据...");
        $this->truncateOld();
        $file = public_path('resources/temp/') . 'screen_customer_merge.xlsx';
        if (!is_file($file)) {
            $this->logger->error("file is not exist!");
            return;
        }
        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($file);
        $worksheet = $spreadsheet->getActiveSheet();
        $rowCount = $worksheet->getHighestRow();
        for ($i = 2; $i <= $rowCount; $i++) {
            $tempIndex = $i - 2;
            $tempTotal = $rowCount - 2;
            $this->logger->info("导入数据: {$tempTotal} ~ {$tempIndex}");
            $customerNumber = trim($worksheet->getCellByColumnAndRow(1, $i)->getValue() ?? '');
            $customerName = trim($worksheet->getCellByColumnAndRow(2, $i)->getValue() ?? '');
            $customerShortName = trim($worksheet->getCellByColumnAndRow(3, $i)->getValue() ?? '');
            $productName = trim($worksheet->getCellByColumnAndRow(4, $i)->getValue() ?? '');
            $productModel = trim($worksheet->getCellByColumnAndRow(5, $i)->getValue() ?? '');
            try {
                $productDate = trim($worksheet->getCellByColumnAndRow(6, $i)->getValue() ?? '');
                $productDate = Carbon::parse(\PHPExcel_Shared_Date::ExcelToPHP($productDate))->toDateString();
            } catch (\Exception $e) {
                $productDate = '';
                $this->logger->info("{$productName} 出厂时间异常， 不导入");
            }
            if ($productDate) {
                $itemData = [
                    'customer_number' => $customerNumber,
                    'customer_name' => $customerName,
                    'customer_short_name' => $customerShortName,
                    'product_name' => $productName,
                    'product_model' => $productModel,
                    'product_date' => $productDate
                ];
                $screenCustomerTemp = new ScreenCustomerTemp();
                $screenCustomerTemp->fill($itemData);
                $screenCustomerTemp->saveOrFail();
            }
        }
    }

    private function truncateOld()
    {
        $this->logger->info("清空旧数据 start...");
        ScreenCustomerTemp::query()->truncate();
        $this->logger->info("清空旧数据 complete...");
    }
}
